package com.cfswt.tasksystem.controller;

import com.cfswt.tasksystem.mapper.*;
import com.cfswt.tasksystem.pojo.dto.*;
import com.cfswt.tasksystem.pojo.entity.*;
import com.cfswt.tasksystem.pojo.vo.*;
import com.cfswt.tasksystem.response.JsonResult;
import com.cfswt.tasksystem.security.CustomUserDetails;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.api.runtime.shared.query.Page;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.api.task.model.Task;
import org.activiti.api.task.model.builders.TaskPayloadBuilder;
import org.activiti.api.task.runtime.TaskRuntime;
import org.activiti.bpmn.model.FormProperty;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.*;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.Execution;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/task")
@Api(tags = "10.任务模块")
public class TaskController {
    @Autowired(required = false)
    private TaskMapper taskMapper;
    @Autowired
    private TaskAttachmentMapper taskAttachmentMapper;
    @Autowired
    private TaskSummaryMapper taskSummaryMapper;
    @Autowired
    private TaskMilestoneMapper taskMilestoneMapper;
    @Autowired
    private TaskCommentMapper taskCommentMapper;
    @Autowired
    private TaskRuntime taskRuntime;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ProcessRuntime processRuntime;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TaskCompleteSummaryMapper taskCompleteSummaryMapper;
    @Autowired
    private TaskPlanSummaryMapper taskPlanSummaryMapper;
    @Autowired
    private TaskCoordinateSummaryMapper taskCoordinateSummaryMapper;
    @Autowired
    private TaskDelayMapper taskDelayMapper;
    @Autowired
    private ReminderMapper reminderMapper;
    @Autowired
    private ReminderUserMapper reminderUserMapper;
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;
    @Autowired
    private MeetingDecisionMapper meetingDecisionMapper;
    @Autowired
    private TaskCategoryMapper taskCategoryMapper;

    @GetMapping("")
    @ApiOperation(value = "获取当前用户待办任务列表")
    public JsonResult getToDoTasks() {
        Page<org.activiti.api.task.model.Task> tasks = taskRuntime.tasks(Pageable.of(0, 100));
        List<HashMap<String, Object>> listMap = new ArrayList<HashMap<String, Object>>();
        for (org.activiti.api.task.model.Task task : tasks.getContent()) {
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("ID_", task.getId());
            hashMap.put("NAME_", task.getName());
            hashMap.put("DISCRIPTION_", task.getDescription());
            hashMap.put("CREATE_TIME_", task.getCreatedDate());
            if (task.getAssignee() == null) {
                hashMap.put("conder", "待拾取任务");
            } else {
                hashMap.put("assignee", task.getAssignee());
            }
            String processInstanceId = task.getProcessInstanceId();
            hashMap.put("PROC_INST_ID_", processInstanceId);
            ProcessInstance processInstance = processRuntime.processInstance(processInstanceId);
            String businessKey = processInstance.getBusinessKey();
            hashMap.put("BUSINESS_KEY", businessKey);
            listMap.add(hashMap);
        }
        System.out.println(listMap);
        return JsonResult.ok(listMap);
    }

    @ApiOperation("获取当前用户待办任务数量")
    @GetMapping("/todo/count")
    public JsonResult selectTodoTaskCount() {
        Page<Task> tasks = taskRuntime.tasks(Pageable.of(0, 1000));
        int totalItems = tasks.getTotalItems();
        Map<String, String> processKeys = new HashMap<>();
        processKeys.put("Process_1:2:e1e583d7-6b61-11f0-8fb7-185e0fbeb34d", "物资入库申请");
        processKeys.put("Process_2:10:962e2511-86e3-11f0-ab69-185e0fbeb34d", "物资出库申请");
        processKeys.put("Process_3:2:bf9ee1b2-89fc-11f0-89be-185e0fbeb34d", "任务发布流程");
        processKeys.put("Process_4:1:3f7ecf37-4412-11ef-af7c-185e0fbeb34d", "项目管理流程");
        processKeys.put("Process_5:4:27488285-89fd-11f0-89be-185e0fbeb34d", "分解任务流程");
        processKeys.put("Process_6:1:e61b73db-b2b8-11ef-a526-185e0fbeb34d", "搅拌头业务流程");
        processKeys.put("Process_7:3:dbb7d898-89ff-11f0-89be-185e0fbeb34d", "会议任务发布流程");
        processKeys.put("Process_8:7:1d7c3dcb-8a00-11f0-89be-185e0fbeb34d", "发起会议流程");
        processKeys.put("Process_9:9:4890e0b1-8a01-11f0-89be-185e0fbeb34d", "党建方案审批流程");

        Map<String, Long> todoTaskCounts = new HashMap<>();
        for (Map.Entry<String, String> entry : processKeys.entrySet()) {
            String key = entry.getKey();
            Long count = tasks.getContent().stream().filter(task -> task.getProcessDefinitionId().equals(key)).count();
            todoTaskCounts.put(entry.getValue(), count);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("total", totalItems);
        result.put("details", todoTaskCounts);
        System.out.println(result);
        return JsonResult.ok(result);
    }

    @ApiOperation(value = "根据任务id获取对应表单组件")
    @GetMapping("/view/{taskId}")
    public JsonResult viewTask(@PathVariable String taskId) {
        System.out.println("任务id" + taskId);
        org.activiti.api.task.model.Task task = taskRuntime.task(taskId);
        String formKey = task.getFormKey();
        System.out.println("对应的表单" + formKey);
        return JsonResult.ok(formKey);
    }

    @ApiOperation(value = "根据任务id渲染历史节点")
    @GetMapping("/formDataShow")
    public JsonResult formData(String taskId) {
        org.activiti.api.task.model.Task task = taskRuntime.task(taskId);
        UserTask userTask = (UserTask) repositoryService.getBpmnModel(task.getProcessDefinitionId())
                .getFlowElement(task.getFormKey());
        List<FormProperty> formProperties = userTask.getFormProperties();
        for (FormProperty formProperty : formProperties) {
            //formProperty.getName();
        }
        ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();
        RepositoryService
                repositoryService = engine.getRepositoryService();


        return JsonResult.ok(formProperties);
    }

    @ApiOperation(value = "发布任务")
    @Transactional
    @PostMapping("/release")
    public JsonResult releaseTask(@RequestBody ReleaseTaskDTO releaseTaskDTO,
                                  @AuthenticationPrincipal CustomUserDetails userDetails) {
        processTask(releaseTaskDTO, "Process_3", userDetails);
        return JsonResult.ok();
    }

    @ApiOperation(value = "拆解任务")
    @Transactional
    @PostMapping("/releaseSubTask")
    public JsonResult releaseSubTask(@RequestBody List<ReleaseTaskDTO> releaseTaskDTOS,
                                     @AuthenticationPrincipal CustomUserDetails userDetails) {
        Map<String, Object> variables = new HashMap<>();
        for (ReleaseTaskDTO releaseTaskDTO : releaseTaskDTOS) {
            processTask(releaseTaskDTO, "Process_3", userDetails);
        }
        return JsonResult.ok();
    }

    @ApiOperation(value = "将会议决策发布为任务")
    @Transactional
    @PostMapping("/record/release/")
    public JsonResult applyMeetingTasks(@RequestBody List<ReleaseTaskDTO> meetingTasks,
                                        @AuthenticationPrincipal CustomUserDetails userDetails) {
        String creator = userDetails.getUsername();
        String processDefinitionKey = "Process_3";
        for (ReleaseTaskDTO meetingTask : meetingTasks) {
            String agent = meetingTask.getReportBy();
            String userName = userMapper.selectUserNameByNickName(agent);
            Integer count = meetingTask.getReportCount();
            String frequency = meetingTask.getFrequency();
            String timeUnit = convertToISO8601Unit(frequency);
            Integer categoryId = meetingTask.getCategoryId();
            String bussinessKey = "会议任务发布" + userDetails.getNickName();
            Map<String, Object> variables = new HashMap<>();
            variables.put("agent", userName);
            variables.put("creator", creator);
            variables.put("reportCount", count);
            variables.put("reportComplete", 0);
            variables.put("categoryId", 4);
            variables.put("timeUnit", timeUnit);
            Authentication.setAuthenticatedUserId(userDetails.getNickName());
            String processInstanceId = runtimeService.startProcessInstanceByKey(processDefinitionKey, bussinessKey, variables)
                    .getProcessInstanceId();
            int statusId = 1;
            meetingTask.setReleaseBy(userDetails.getNickName()).setSn(generateTaskSN()).setCreateTime(new Date())
                    .setReportComplete(0).setStatusId(statusId).setProcessInstanceId(processInstanceId)
                    .setProjectSn(null);
            CfswtTask cfswtTask = new CfswtTask();
            BeanUtils.copyProperties(meetingTask, cfswtTask);
/*            if(taskMapper.selectTaskById(cfswtTask.getId())){
                taskMapper.updateTaskById(cfswtTask);
                Integer id = cfswtTask.getId();
                List<ContentSummary> contentSummaries = meetingTask.getContentSummaries();
                for (ContentSummary contentSummary : contentSummaries) {
                    taskSummaryMapper.updateContentSummaryById(id);
                }
            }else {*/
            taskMapper.insertCfswtTask(cfswtTask);
            Integer id = cfswtTask.getId();
            System.out.println("会议任务的id是：" + id);
            Integer decisionId = meetingTask.getDecisionId();
            List<ContentSummary> contentSummaries = meetingTask.getContentSummaries();
            for (ContentSummary contentSummary : contentSummaries) {
                contentSummary.setTaskContentId(id);
                taskSummaryMapper.addTaskSummary(contentSummary);
                /*                }*/
            }
            System.out.println("经过丰富后的会议任务数据是：" + meetingTask);
            meetingDecisionMapper.setMeetingDecisionTaskIdById(decisionId, id);
        }
        return JsonResult.ok();
    }

    @ApiOperation(value = "将kpi工作计划发布为任务")
    @Transactional
    @PostMapping("/kpi/release/")
    public JsonResult applyKpiSchemeTasks(@RequestBody List<ReleaseTaskDTO> schemeTasks,
                                          @AuthenticationPrincipal CustomUserDetails userDetails) {
        System.out.println(schemeTasks);
        for (ReleaseTaskDTO schemeTask : schemeTasks) {
            processTask(schemeTask, "Process_3", userDetails);
        }
        System.out.println("kpi任务数据为：" + schemeTasks);
        return JsonResult.ok();
    }

    private void processTask(ReleaseTaskDTO releaseTaskDTO, String processDefinitionKey, CustomUserDetails userDetails) {
        String creator = userDetails.getUsername();
        String agent = releaseTaskDTO.getReportBy();
        String userName = userMapper.selectUserNameByNickName(agent);
        Integer count = releaseTaskDTO.getReportCount();
        String frequency = releaseTaskDTO.getFrequency();
        String timeUnit = convertToISO8601Unit(frequency);
        Integer categoryId = releaseTaskDTO.getCategoryId();
        String bussinessKey = "任务发布" + userDetails.getNickName();
        Map<String, Object> variables = new HashMap<>();
        variables.put("agent", userName);
        variables.put("creator", creator);
        variables.put("reportCount", count);
        variables.put("reportComplete", 0);
        variables.put("timeUnit", timeUnit);
        variables.put("categoryId", categoryId);
        Authentication.setAuthenticatedUserId(userDetails.getNickName());
        String processInstanceId = runtimeService.startProcessInstanceByKey(processDefinitionKey, bussinessKey, variables)
                .getProcessInstanceId();
        org.activiti.engine.task.Task userTask = taskService.createTaskQuery()
                .processInstanceId(processInstanceId)
                .taskAssignee(creator) // 指定任务办理人
                .singleResult();
        System.out.println("Task Name: " + userTask);
        if ("任务发布".equals(userTask.getName())) {
            taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(userTask.getId()).build());
        }
        Date today = new Date();
        int statusId = 1;/*默认进行中*/
        releaseTaskDTO.setReleaseBy(userDetails.getNickName()).setSn(generateTaskSN()).setCreateTime(new Date()).setProcessInstanceId(processInstanceId)
                .setReportBy(agent).setReportComplete(0).setStatusId(statusId);
        CfswtTask cfswtTask = new CfswtTask();
        BeanUtils.copyProperties(releaseTaskDTO, cfswtTask);
        System.out.println(cfswtTask);
        taskMapper.insertCfswtTask(cfswtTask);
        Integer id = cfswtTask.getId();
        List<ContentSummary> contentSummaries = releaseTaskDTO.getContentSummaries();
        for (ContentSummary contentSummary : contentSummaries) {
            contentSummary.setTaskContentId(id);
            taskSummaryMapper.addTaskSummary(contentSummary);
        }
        List<TaskMilestone> taskMilestones = releaseTaskDTO.getTaskMilestones();
        for (TaskMilestone taskMilestone : taskMilestones) {
            taskMilestone.setTaskId(id);
            taskMilestoneMapper.addTaskMilestone(taskMilestone);
        }
        List<TaskAttachment> attachments = releaseTaskDTO.getReleaseAttachments();
        for (TaskAttachment attachment : attachments) {
            attachment.setTaskId(id).setCreateBy(creator).setCreateTime(new Date());
            taskAttachmentMapper.insertAttachment(attachment);
        }
        System.out.println(releaseTaskDTO);
        ReminderVO reminderVO = new ReminderVO();
        reminderVO.setRemindTime(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(releaseTaskDTO.getStartTime()));
        reminderVO.setTime(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));
        reminderVO.setRelatedId(id.toString());
        reminderVO.setType("任务通知");
        reminderVO.setSender(userDetails.getNickName());
        reminderVO.setTitle(releaseTaskDTO.getTitle());
        reminderVO.setSummary(releaseTaskDTO.getProjectSn());
        reminderVO.setStatus(ReminderVO.Status.fromString("未读"));
        reminderMapper.insertReminder(reminderVO);
        Integer reminderVOId = reminderVO.getId();
        Integer userId = userMapper.selectIdByNickName(agent);
        ReminderUser reminderUser = new ReminderUser();
        reminderUser.setUserId(userId);
        reminderUser.setReminderId(reminderVOId);
        reminderUser.setCreateTime(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));
        reminderUserMapper.insertReminderUser(reminderUser);
        System.out.println("Sending message to user: " + userName + " at /queue/meeting-notification");
        simpMessagingTemplate.convertAndSendToUser(userName, "/queue/meeting-notification", reminderVO);
        System.out.println(reminderVO);
    }

    private String generateTaskSN() {
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 格式化日期
        String formattedDate = today.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        // 查询今天已经生成的任务数量
        Integer todayCount = taskMapper.countTasksByDate(today);
        // 生成流水号，确保是3位数，不足前面补0
        String serialNumber = String.format("%03d", todayCount + 1);
        // 拼接成完整的任务编号
        return formattedDate + serialNumber;
    }

    public String convertToISO8601Unit(String chineseUnit) {
        switch (chineseUnit) {
            case "天":
                return "D";
            case "周":
                return "7D";
            case "月":
                return "M";
            default:
                throw new IllegalArgumentException("不被支持的日期单位: " + chineseUnit);
        }
    }

    @ApiOperation(value = "更新KPI工作计划任务顺序")
    @PostMapping("/sort/")
    public JsonResult updateTaskSortBatch(@RequestBody List<SchemeTaskSortDTO> schemeTaskSortDTOS) {
        for (SchemeTaskSortDTO schemeTaskSortDTO : schemeTaskSortDTOS) {
            taskMapper.updateTaskSortBatch(schemeTaskSortDTO);
        }
        return JsonResult.ok();
    }

    @ApiOperation(value = "显示汇报内容")
    @GetMapping("/reportTask/{taskId}")
    public JsonResult selectReportTask(@PathVariable String taskId) {
        org.activiti.api.task.model.Task task = taskRuntime.task(taskId);
        String processInstanceId = task.getProcessInstanceId();
        ReportTaskVO reportTaskVO = taskMapper.selectTaskByProcessInstanceId(processInstanceId);
        List<ContentSummary> contentSummaries = taskSummaryMapper.selectContentSummariesByTaskId(reportTaskVO.getId());
        reportTaskVO.setContentSummaries(contentSummaries);
/*        List<TaskAttachment> taskAttachments = taskAttachmentMapper.selectAttachmentByTaskId(reportTaskVO.getId());
        reportTaskVO.setAttachment(taskAttachments);*/
        System.out.println(reportTaskVO);
        return JsonResult.ok(reportTaskVO);
    }

    @ApiOperation(value = "汇报任务")
    @Transactional
    @PostMapping("/reportTask")
    public JsonResult reportTask(@RequestBody ReportTaskDTO reportTaskDTO,
                                 @AuthenticationPrincipal CustomUserDetails userDetails) {
        System.out.println(reportTaskDTO);
        String processInstanceId = reportTaskDTO.getProcessInstanceId();
        for (TaskCompleteSummary taskCompleteSummary : reportTaskDTO.getTaskCompleteSummaries()) {
            taskCompleteSummary.setCreateTime(new Date());
            taskCompleteSummary.setCreateBy(userDetails.getNickName());
            taskCompleteSummary.setTaskId(reportTaskDTO.getTaskId());
            if (taskCompleteSummary.getId() != null) {
                taskCompleteSummaryMapper.updateTaskCompleteSummary(taskCompleteSummary);
                System.out.println("更新方法执行了");
            } else {
                int id = reportTaskDTO.getTaskId();
                int reportComplete = taskMapper.selectReportCompleteByTaskId(reportTaskDTO.getTaskId());
                taskCompleteSummaryMapper.addTaskCompleteSummary(taskCompleteSummary);
                reportComplete++;
                taskMapper.updateReportCompleteByTaskId(id, reportComplete);
                System.out.println("增加汇报次数的方法执行了");
            }
        }
        for (TaskPlanSummary taskPlanSummary : reportTaskDTO.getTaskPlanSummaries()) {
            taskPlanSummary.setCreateTime(new Date());
            taskPlanSummary.setCreateBy(userDetails.getNickName());
            taskPlanSummary.setTaskId(reportTaskDTO.getTaskId());
            if (taskPlanSummary.getId() != null) {
                taskPlanSummaryMapper.updateTaskPlanSummary(taskPlanSummary);
            } else {
                taskPlanSummaryMapper.addTaskPlanSummary(taskPlanSummary);
                TaskCompleteSummary newTaskCompleteSummary = new TaskCompleteSummary();
                newTaskCompleteSummary.setTaskId(reportTaskDTO.getTaskId());
                newTaskCompleteSummary.setWeekLabel(taskPlanSummary.getWeekLabel()); // 假设下周为当前周标签+1
                newTaskCompleteSummary.setTaskComplete(""); // 初始为空
                newTaskCompleteSummary.setCreateTime(new Date());
                newTaskCompleteSummary.setCreateBy(userDetails.getNickName());
                taskCompleteSummaryMapper.addTaskCompleteSummary(newTaskCompleteSummary);
            }
        }
        for (TaskCoordinateSummary taskCoordinateSummary : reportTaskDTO.getTaskCoordinateSummaries()) {
            taskCoordinateSummary.setCreateTime(new Date());
            taskCoordinateSummary.setCreateBy(userDetails.getNickName());
            taskCoordinateSummary.setTaskId(reportTaskDTO.getTaskId());
            if (taskCoordinateSummary.getId() != null) {
                taskCoordinateSummaryMapper.updateTaskCoordinateSummary(taskCoordinateSummary);
            } else {
                taskCoordinateSummaryMapper.addTaskCoordinateSummary(taskCoordinateSummary);
            }
        }
        List<TaskAttachment> taskAttachments = reportTaskDTO.getTaskAttachments();
        for (TaskAttachment taskAttachment : taskAttachments) {
            taskAttachment.setTaskId(reportTaskDTO.getTaskId()).setCreateBy(userDetails.getNickName()).setCreateTime(new Date());
            taskAttachmentMapper.insertOrUpdateTaskAttachment(taskAttachment);
        }
        return JsonResult.ok();
    }

    @ApiOperation(value = "提交评论")
    @PostMapping("/comment")
    public JsonResult submitComment(@RequestBody TaskCommentSummary taskCommentSummary, @AuthenticationPrincipal CustomUserDetails userDetails) {
        taskCommentSummary.setCreateBy(userDetails.getNickName());
        taskCommentSummary.setCreateTime(new Date());
        List<TaskAttachment> taskAttachments = taskCommentSummary.getTaskAttachments();
        for (TaskAttachment taskAttachment : taskAttachments) {
            taskAttachment.setTaskId(taskCommentSummary.getTaskId()).setCreateBy(userDetails.getNickName()).setCreateTime(new Date());
            taskAttachmentMapper.insertAttachment(taskAttachment);
        }
        taskCommentMapper.addTaskComment(taskCommentSummary);
        return JsonResult.ok();
    }

    @ApiOperation(value = "")
    @Transactional
    @GetMapping("/approval/{taskId}")
    public JsonResult selectApprovalTask(@PathVariable String taskId, @AuthenticationPrincipal CustomUserDetails userDetails) {
        org.activiti.api.task.model.Task task = taskRuntime.task(taskId);
        String processInstanceId = task.getProcessInstanceId();
        ApprovalTaskVO approvalTaskVO = taskMapper.selectApprovalTaskByInstanceId(processInstanceId);
        Integer id = approvalTaskVO.getId();
        List<ContentSummary> contentSummaries = taskSummaryMapper.selectContentSummariesByTaskId(id);
        approvalTaskVO.setContentSummaries(contentSummaries);
        List<TaskAttachment> taskAttachments = taskAttachmentMapper.selectAttachmentByTaskId(id);
        approvalTaskVO.setAttachment(taskAttachments);
        List<TaskCompleteSummary> taskCompleteSummaries = taskCompleteSummaryMapper.selectCompleteSummariesByTaskId(id);
        approvalTaskVO.setTaskCompleteSummaries(taskCompleteSummaries);
        List<TaskPlanSummary> taskPlanSummaries = taskPlanSummaryMapper.selectPlanSummariesByTaskId(id);
        approvalTaskVO.setTaskPlanSummaries(taskPlanSummaries);
        List<TaskCoordinateSummary> taskCoordinateSummaries = taskCoordinateSummaryMapper.selectCoordinateSummariesByTaskId(id);
        approvalTaskVO.setTaskCoordinateSummaries(taskCoordinateSummaries);
        Authentication.setAuthenticatedUserId(userDetails.getNickName());
        taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(taskId).build());
        System.out.println(approvalTaskVO);
        return JsonResult.ok(approvalTaskVO);
    }

    // 映射到“ganttReport”路径的方法，用于初始化基于报告人的甘特图数据
    @GetMapping("ganttReport")
    public JsonResult initGantt(@AuthenticationPrincipal CustomUserDetails customUserDetails) {
        return initGanttByType(customUserDetails.getNickName(), "report", null);
    }

    // 映射到“ganttRelease”路径的方法，用于初始化基于发布人的甘特图数据
    @GetMapping("ganttRelease")
    public JsonResult initGanttRelease(@AuthenticationPrincipal CustomUserDetails customUserDetails) {
        return initGanttByType(customUserDetails.getNickName(), "release", null);
    }

    // 映射到“ganttAll”路径的方法，用于初始化所有人的甘特图数据
    @GetMapping("ganttAll")
    public JsonResult initGanttAll() {
        return initGanttByType(null, "all", null);
    }

    @ApiOperation(value = "根据taskId获取下属任务")
    @GetMapping("subTask/{id}")
    public JsonResult initGanttSubTask(@PathVariable Integer id) {
        return initGanttByType(null, "subTask", id);
    }

    @ApiOperation(value = "负责人发起完成任务申请")
    @Transactional
    @PostMapping("/completeApply")
    public JsonResult applyTaskComplete(@RequestBody TaskCompleteApplyDTO taskCompleteApplyDTO, @AuthenticationPrincipal CustomUserDetails userDetails) {
        Integer taskId = taskCompleteApplyDTO.getTaskId();
        taskCompleteApplyDTO.setCreateTime(new Date());
        taskCompleteApplyDTO.setApplicant(userDetails.getNickName());
        taskMapper.insertTaskCompleteApply(taskCompleteApplyDTO);
        List<TaskAttachment> taskAttachments = taskCompleteApplyDTO.getTaskAttachments();
        for (TaskAttachment taskAttachment : taskAttachments) {
            taskAttachment.setTaskId(taskId).setCreateBy(userDetails.getNickName()).setCreateTime(new Date());
            taskAttachmentMapper.insertAttachment(taskAttachment);
        }
        CfswtTask cfswtTask = taskMapper.selectTaskInfoByTaskId(taskCompleteApplyDTO.getTaskId());
        System.out.println(cfswtTask);
        String reportBy = cfswtTask.getReportBy();
        String title = cfswtTask.getTitle();
        ReminderVO reminderVO = new ReminderVO();
        reminderVO.setRemindTime(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(taskCompleteApplyDTO.getCreateTime()));
        reminderVO.setTime(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));
        reminderVO.setRelatedId(taskId.toString());
        reminderVO.setType("党建任务完成申请");
        reminderVO.setSender(reportBy);
        reminderVO.setTitle(title);
        reminderVO.setSummary(taskCompleteApplyDTO.getDescription());
        reminderVO.setStatus(ReminderVO.Status.fromString("未读"));
        System.out.println(reminderVO);
        reminderMapper.insertReminder(reminderVO);
        Integer reminderVOId = reminderVO.getId();
        Integer userId = userMapper.selectIdByNickName(reportBy);
        ReminderUser reminderUser = new ReminderUser();
        reminderUser.setUserId(userId);
        reminderUser.setReminderId(reminderVOId);
        reminderUser.setCreateTime(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));
        reminderUserMapper.insertReminderUser(reminderUser);
        System.out.println("Sending message to user: " + reportBy + " at /queue/meeting-notification");
        simpMessagingTemplate.convertAndSendToUser(reportBy, "/queue/meeting-notification", reminderVO);
        System.out.println(reminderVO);
        return JsonResult.ok();
    }

    @ApiOperation(value = "发布人显示待审批的任务完成申请")
    @Transactional
    @GetMapping("/complete/{id}")
    public JsonResult applyTaskComplete(@PathVariable Integer id) {
        TaskCompleteApplyVO latestTaskCompleteVO = null;
        TaskCompleteApplyVO taskCompleteApplyVO = taskMapper.selectTaskCompleteLatestApplyByTaskId(id);
        if (taskCompleteApplyVO == null) {
            JsonResult.error(2002, "没有申请记录");
        }
        if (taskCompleteApplyVO.getApprover() == null) {
            latestTaskCompleteVO = taskCompleteApplyVO;
            List<TaskAttachment> taskAttachments = taskAttachmentMapper.selectAttachmentByTaskId(id);
            latestTaskCompleteVO.setTaskAttachments(taskAttachments);
            return JsonResult.ok(latestTaskCompleteVO);
        } else {
            return JsonResult.ok(latestTaskCompleteVO);
        }
    }

    @ApiOperation(value = "显示完成申请的历史数据")
    @Transactional
    @GetMapping("/allComplete/{id}")
    public JsonResult selectTaskCompleteApply(@PathVariable Integer id, @AuthenticationPrincipal CustomUserDetails userDetails) {
        List<TaskHistoryCompleteVO> taskHistoryCompleteVOS = taskMapper.selectTaskCompleteApplyByTaskId(id);
        for (TaskHistoryCompleteVO taskHistoryCompleteVO : taskHistoryCompleteVOS) {
            taskHistoryCompleteVO.setApprover(userDetails.getNickName());
            taskHistoryCompleteVO.setApprovalTime(new Date());
            List<TaskAttachment> taskAttachments = taskAttachmentMapper.selectAttachmentByTaskId(id);
            List<TaskAttachment> filteredAttachments = taskAttachments.stream()
                    .filter(att -> "完成申请时".equals(att.getSource()))
                    .collect(Collectors.toList());
            taskHistoryCompleteVO.setTaskAttachments(filteredAttachments);
        }
        return JsonResult.ok(taskHistoryCompleteVOS);
    }

    @ApiOperation(value = "党支部书记显示待审批的任务完成申请")
    @Transactional
    @GetMapping("/complete/party/{taskId}")
    public JsonResult selectTaskCompleteApply(@PathVariable String taskId) {
        String processInstanceId = taskRuntime.task(taskId).getProcessInstanceId();
        int id = taskMapper.selectTaskIdByProcessInstanceId(processInstanceId);
        String title = taskMapper.selectTaskInfoByTaskId(id).getTitle();
        TaskCompleteApplyVO latestTaskCompleteVO = null;
        TaskCompleteApplyVO taskCompleteApplyVO = taskMapper.selectTaskCompleteLatestApplyByTaskId(id);
        taskCompleteApplyVO.setTitle(title);
        if (taskCompleteApplyVO == null) {
            JsonResult.error(2002, "没有申请记录");
        }
        latestTaskCompleteVO = taskCompleteApplyVO;
        List<TaskAttachment> taskAttachments = taskAttachmentMapper.selectAttachmentByTaskId(id);
        latestTaskCompleteVO.setTaskAttachments(taskAttachments);
        return JsonResult.ok(latestTaskCompleteVO);
    }


    @ApiOperation(value = "发布人进行完成任务申请的审批")
    @Transactional
    @PostMapping("/complete_apply/review/")
    public JsonResult taskReview(@RequestBody ApprovedCompleteDTO approvedCompleteDTO, @AuthenticationPrincipal CustomUserDetails userDetails) {
        Authentication.setAuthenticatedUserId(userDetails.getNickName());
        Integer taskId = approvedCompleteDTO.getTaskId();
        Integer categoryId = taskCategoryMapper.selectIdByCategoryName(approvedCompleteDTO.getCategoryName());
        System.out.println(approvedCompleteDTO);
        if (categoryId == 3) {
            System.out.println("执行到这里了");
            List<Execution> executions = runtimeService.createExecutionQuery()
                    .processInstanceId(approvedCompleteDTO.getProcessInstanceId())
                    .signalEventSubscriptionName("partyCompleteSignal")
                    .list();
            System.out.println(executions);
            for (Execution execution : executions) {
                System.out.println("等待信号的执行路径 ID: " + execution.getId());
                runtimeService.signalEventReceived("partyCompleteSignal", execution.getId());
            }
        } else {
            List<Execution> executions = runtimeService.createExecutionQuery()
                    .processInstanceId(approvedCompleteDTO.getProcessInstanceId())
                    .signalEventSubscriptionName("completeSignal")
                    .list();
            for (Execution execution : executions) {
                System.out.println("等待信号的执行路径 ID: " + execution.getId());
                runtimeService.signalEventReceived("completeSignal", execution.getId());
            }
        }
        approvedCompleteDTO.setApprovalTime(new Date());
        approvedCompleteDTO.setApprover(userDetails.getNickName());
        taskMapper.updateTaskCompleteApplyByTaskId(approvedCompleteDTO);
        taskMapper.updateTaskCompleteTimeById(taskId, approvedCompleteDTO.getActualFinishingTime());
        return JsonResult.ok();
    }

    @ApiOperation(value = "党支部书记审批党建任务的完成申请")
    @Transactional
    @PostMapping("/complete_apply/approval/{taskId}")
    public JsonResult taskApproval(@PathVariable String taskId) {
        String processInstanceId = taskRuntime.task(taskId).getProcessInstanceId();
        org.activiti.engine.task.Task userTask = taskService.createTaskQuery()
                .processInstanceId(processInstanceId)
                .taskAssignee("mengqiang") // 指定任务办理人
                .singleResult();
        System.out.println("Task Name: " + userTask);
        if ("党支部书记审批".equals(userTask.getName())) {
            taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(userTask.getId()).build());
        }
        int i = taskMapper.selectTaskIdByProcessInstanceId(processInstanceId);
        taskMapper.updateTaskStatusByTaskId(i, 3);
        return JsonResult.ok();
    }


    // 私有方法，根据用户名和类型初始化甘特图数据
    private JsonResult initGanttByType(String userName, String type, Integer id) {
        List<GanttTaskVO> ganttTaskVOS;
        switch (type) {
            case "report":
                ganttTaskVOS = taskMapper.selectGanttTasksByReportName(userName);
                break;
            case "release":
                ganttTaskVOS = taskMapper.selectGanttTasksByReleaseName(userName);
                break;
            case "all":
                ganttTaskVOS = taskMapper.selectAllGanttTasks();
                break;
            case "subTask":
                ganttTaskVOS = taskMapper.selectGannttTasksByParentId(id);
                break;
            default:
                return JsonResult.error(400, "无效的类型");
        }
        for (GanttTaskVO ganttTaskVO : ganttTaskVOS) {
            // 查询待审批完成申请数据
            TaskCompleteApplyVO taskCompleteApplyVO = taskMapper.selectTaskCompleteLatestApplyByTaskId(ganttTaskVO.getId());
            if (taskCompleteApplyVO != null && taskCompleteApplyVO.getApprover() == null) {
                ganttTaskVO.setLatestTaskCompleteApplyVO(taskCompleteApplyVO);
                List<TaskAttachment> taskAttachments = taskAttachmentMapper.selectAttachmentByTaskId(ganttTaskVO.getId());
                List<TaskAttachment> filteredAttachments = taskAttachments.stream()
                        .filter(att -> "完成申请时".equals(att.getSource()))
                        .collect(Collectors.toList());
                taskCompleteApplyVO.setTaskAttachments(filteredAttachments);
            }
            List<TaskDelayVO> taskDelayVOS = taskDelayMapper.selectTaskDelayById(ganttTaskVO.getProcessInstanceId());
            if (taskDelayVOS != null) {
                for (TaskDelayVO taskDelayVO : taskDelayVOS) {
                    if (taskDelayVO.getDelayApprovedDate() == null) {
                        if (ganttTaskVO.getLatestTaskDelayApplyVO() == null) {
                            ganttTaskVO.setLatestTaskDelayApplyVO(taskDelayVO);
                        } else if (taskDelayVO.getDelayProposedDate().after(ganttTaskVO.getLatestTaskDelayApplyVO().getDelayProposedDate())) {
                            ganttTaskVO.setLatestTaskDelayApplyVO(taskDelayVO);
                        }
                    }
                }
            }
            enrichGanttTaskVO(ganttTaskVO);
        }
        System.out.println(ganttTaskVOS);
        return JsonResult.ok(ganttTaskVOS);
    }

    // 辅助方法，用于丰富GanttTaskVO对象的数据，为各种性质的任务增加了发布时附件、汇报时数据、评论时附件、历史延期数据、任务纪要、计划纪要、完成纪要、协调纪要以及评论纪要数据
    // 其他任务字段都在上面方法中对应的taskMapper中获得。
    private void enrichGanttTaskVO(GanttTaskVO ganttTaskVO) {
        try {
            Integer id = ganttTaskVO.getId();
            String processInstanceId = ganttTaskVO.getProcessInstanceId();
            List<TaskAttachment> taskAttachments = taskAttachmentMapper.selectAttachmentByTaskId(id);
            List<TaskAttachment> releaseAttachments = new ArrayList<>();
            List<TaskAttachment> reportAttachments = new ArrayList<>();
            List<TaskAttachment> commentAttachments = new ArrayList<>();
            for (TaskAttachment taskAttachment : taskAttachments) {
                switch (taskAttachment.getSource()) {
                    case "发布时":
                        releaseAttachments.add(taskAttachment);
                        break;
                    case "汇报时":
                        reportAttachments.add(taskAttachment);
                        break;
                    case "评论时":
                        commentAttachments.add(taskAttachment);
                        break;
                }
            }
            ganttTaskVO.setReleaseAttachments(releaseAttachments);
            ganttTaskVO.setReportAttachments(reportAttachments);
            ganttTaskVO.setCommentAttachments(commentAttachments);
            List<TaskHistoryDelayVO> taskHistoryDelayVOS = taskDelayMapper.selectTaskHistoryDelayById(processInstanceId);
            // 处理延期状态
            Date now = new Date();
            Date taskEndDate = taskMapper.selectTaskEndDateById(id);
            boolean isDelayed = taskHistoryDelayVOS == null || taskHistoryDelayVOS.isEmpty();
            if (now.after(taskEndDate) && isDelayed) {
                ganttTaskVO.setStatusName("已延期");
            }
            if (taskHistoryDelayVOS != null) {
                List<TaskHistoryDelayVO> approvedDelays = new ArrayList<>();
                Date latestApprovalDate = null;
                for (TaskHistoryDelayVO taskHistoryDelayVO : taskHistoryDelayVOS) {
                    if (taskHistoryDelayVO.getDelayApprovedDate() != null) {
                        approvedDelays.add(taskHistoryDelayVO);
                        if (latestApprovalDate == null || taskHistoryDelayVO.getDelayApprovedDate().after(latestApprovalDate)) {
                            latestApprovalDate = taskHistoryDelayVO.getDelayApprovedDate();
                        }
                    }
                }
                ganttTaskVO.setTaskHistoryDelayVOS(approvedDelays);
                ganttTaskVO.setDelayApprovedDate(latestApprovalDate);
            } else {
                ganttTaskVO.setDelayApprovedDate(taskMapper.selectTaskEndDateById(ganttTaskVO.getId()));
            }
            ganttTaskVO.setContentSummaries(taskSummaryMapper.selectContentSummariesByTaskId(id));
            ganttTaskVO.setTaskMilestones(taskMilestoneMapper.selectTaskMilestoneByTaskId(id));
            ganttTaskVO.setTaskCommentSummaries(taskCommentMapper.selectTaskCommentsByTaskId(id));
            ganttTaskVO.setTaskCompleteSummaries(taskCompleteSummaryMapper.selectCompleteSummariesByTaskId(id));
            ganttTaskVO.setTaskPlanSummaries(taskPlanSummaryMapper.selectPlanSummariesByTaskId(id));
            ganttTaskVO.setTaskCoordinateSummaries(taskCoordinateSummaryMapper.selectCoordinateSummariesByTaskId(id));
        } catch (Exception e) {
            System.out.println("Error processing GanttTaskVO: " + e.getMessage());
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "甘特图中切换任务")
    @GetMapping("detail/{id}")
    public JsonResult selectTaskDetailById(@PathVariable Integer id) {
        GanttTaskVO ganttTaskVO = taskMapper.selectTaskDetailById(id);
        enrichGanttTaskVO(ganttTaskVO);
        return JsonResult.ok(ganttTaskVO);
    }

    @ApiOperation(value = "负责人申请任务延期")
    @Transactional
    @PostMapping("delay")
    public JsonResult taskDelay(@RequestBody TaskDelayDTO taskDelayDTO, @AuthenticationPrincipal CustomUserDetails userDetails) {
        Authentication.setAuthenticatedUserId(userDetails.getNickName());
        String processInstanceId = taskDelayDTO.getProcessInstanceId();
        List<Execution> executions = runtimeService.createExecutionQuery()
                .processInstanceId(processInstanceId)
                .signalEventSubscriptionName("delaySignal")
                .list();
        for (Execution execution : executions) {
            System.out.println("等待信号的执行路径 ID: " + execution.getId());
            Page<Task> tasks = taskRuntime.tasks(Pageable.of(0, 10), TaskPayloadBuilder.tasks()
                    .withProcessInstanceId(taskDelayDTO.getProcessInstanceId())
                    .build());
            tasks.getContent().forEach(task -> System.out.println("查询到的任务: " + task.getName() + " ID: " + task.getId()));
            runtimeService.signalEventReceived("delaySignal", execution.getId());
        }
        TaskDelay taskDelay = new TaskDelay();
        BeanUtils.copyProperties(taskDelayDTO, taskDelay);
        taskDelay.setCreateTime(new Date());
        taskDelayMapper.insertTaskDelay(taskDelay);
        return JsonResult.ok();
    }

    @ApiOperation(value = "显示待审批延期申请信息")
    @GetMapping("delay/{processInstanceId}")
    public JsonResult selectTaskDelayById(@PathVariable String processInstanceId) {
        TaskDelayVO latestTaskDelayVO = null;
        List<TaskDelayVO> taskDelayVOS = taskDelayMapper.selectTaskDelayById(processInstanceId);
        if (taskDelayVOS != null) {
            for (TaskDelayVO taskDelayVO : taskDelayVOS) {
                if (taskDelayVO.getDelayApprovedDate() == null) {
                    if (latestTaskDelayVO == null) {
                        latestTaskDelayVO = taskDelayVO;
                    } else if (taskDelayVO.getDelayProposedDate().after(latestTaskDelayVO.getDelayProposedDate()))
                        latestTaskDelayVO = taskDelayVO;
                }
            }
        }
        System.out.println(latestTaskDelayVO);
        return JsonResult.ok(latestTaskDelayVO);
    }

    @ApiOperation(value = "任务延期审批")
    @Transactional
    @PostMapping("delay/approval/")
    public JsonResult updateTaskDelayById(@RequestBody ApprovedDelayDTO approvedDelayDTO, @AuthenticationPrincipal CustomUserDetails userDetails) {
        Authentication.setAuthenticatedUserId(userDetails.getNickName());
        String processInstanceId = approvedDelayDTO.getProcessInstanceId();
        taskMapper.updateTaskDelayById(approvedDelayDTO);
        taskMapper.updateTaskStatusByProcessInstanceId(processInstanceId, 1);
        return JsonResult.ok();
    }

    @ApiOperation(value = "获取任务用户各种状态任务数量")
    @Transactional
    @GetMapping("/status")
    public JsonResult selectTaskStatus() {
        List<TaskStatusVO> taskStatusVOS = taskMapper.selectTaskStatus();
        return JsonResult.ok(taskStatusVOS);
    }

    @ApiOperation(value = "转交任务")
    @Transactional
    @PostMapping("/transmit/")
    public JsonResult transmitTaskAssignee(@RequestBody TaskTransmitDTO taskTransmitDTO) {
        System.out.println(taskTransmitDTO);
        taskMapper.transmitTaskAssignee(taskTransmitDTO.getId(), taskTransmitDTO.getReportBy());
        org.activiti.engine.task.Task task = taskService.createTaskQuery().processInstanceId(taskTransmitDTO.getProcessInstanceId()).taskName("任务汇报").singleResult();
        taskService.setAssignee(task.getId(), taskTransmitDTO.getReportBy());
        return JsonResult.ok();
    }

}

